package com.quanyan.club.web;

import com.google.common.base.Strings;

import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.club.service.SendTelMsgService;

import com.quanyan.club.sms.ClubSmsService;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import sms.model.Result;

/**
 * @Author Hugo.Wwg
 * @Since 2016-07-25
 */
@RestController
@RequestMapping(value = "/api/club/mobile/")
public class ClubMobileMsgController {

    @Autowired
    private ClubSmsService clubSmsService;

    /**
     * 发送短信
     */
    @RequestMapping(value = "/sendMobileValidatedCode", method = RequestMethod.POST)
    public APIResponse sendMobileValidatedCode(HttpServletRequest request,
                                               @RequestBody Map<String, Object> map) {

        //后续需要控制发送次数限制 , 验证用户身份(如果有必要)等逻辑

        String mobile = MapUtils.getString(map, "mobile");
        if (Strings.isNullOrEmpty(mobile)) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        APIResponse apiResponse = clubSmsService.sendSms(mobile);
        if (!apiResponse.isRet() || apiResponse.getErrcode() != 200){
            return APIResponse.returnFail("短信验证码发送失败");
        }
        return APIResponse.returnSuccess("短信验证码发送成功");
    }

    /**
     * 校验验证码
     */
    @RequestMapping(value = "/verificationCode", method = RequestMethod.POST)
    public APIResponse verificationCode(HttpServletRequest request,
                                        @RequestBody Map<String, Object> map) {
        String validatedCode = MapUtils.getString(map, "validatedCode");
        String mobile = MapUtils.getString(map, "mobile");
        if (Strings.isNullOrEmpty(validatedCode) || Strings.isNullOrEmpty(mobile)) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        APIResponse apiResponse= clubSmsService.checkCode(validatedCode,mobile);
        if (!apiResponse.isRet() || apiResponse.getErrcode() != 200) {
            return APIResponse.returnFail("短信验证码验证失败");
        }
        return APIResponse.returnSuccess("短信验证码验证成功");
    }

}
